<?php

namespace app\admin\model;

use think\Model;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;

/**
 * 带数据范围的基础模型类 (数据表结构必须要有 admin_id, dept_id 字段)
 * 需要用到数据范围的模型类继承该类即可
 */
class Data extends Model
{

    /**
     * 初始化
     */
    protected static function init()
    {
        // select() 查询前回调
        Db::event('before_select', function ($query) {
            self::scope($query);
        });
        // find() 查询前回调
        Db::event('before_find', function ($query) {
            self::scope($query);
        });
        // count() 查询前回调
        Db::event('before_count', function ($query) {
            self::scope($query);
        });
    }

    /**
     * 数据范围
     * @param $query
     */
    protected static function scope($query)
    {
        // 仅本人数据权限
        if (defined('DATA_SCOPE_SELF')) {
            $query->where('admin_id', UID);
        }
        // 本部门数据权限
        if (defined('DATA_SCOPE_DEPT')) {
            $query->where('dept_id', USER->dept_id);
        }
        // 本部门及以下数据权限
        if (defined('DATA_SCOPE_DEPT_ALL')) {
            $query->whereIn('dept_id', DATA_SCOPE_DEPT_ALL);
        }
        // 自定义数据权限
        if (defined('DATA_SCOPE_DEPT_CUSTOM')) {
            $query->whereIn('dept_id', DATA_SCOPE_DEPT_CUSTOM);
        }
    }

    /**
     * 导出 Excel
     * @param $name 文件名
     * @param $data 数据
     * @return string 导出文件路径
     */
    public static function export($name, $data)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($name);
        // 设置表头
        $headers = array_keys($data[0]);
        $column = 'A';
        foreach ($headers as $header) {
            $sheet->setCellValue($column . '1', $header);
            $column++;
        }
        // 填充数据
        $row = 2;
        foreach ($data as $rowData) {
            $column = 'A';
            foreach ($rowData as $value) {
                $sheet->setCellValue($column . $row, $value);
                $column++;
            }
            $row++;
        }
        $filename = time() . $name . '.xls';
        $writer = new Xls($spreadsheet);
        $p_path = public_path() . 'temp/excel/';
        if (!is_dir($p_path)) {
            mkdir($p_path, 0777, true);
        }
        $r_path = runtime_path() . 'temp/';
        if (!is_dir($r_path)) {
            mkdir($r_path, 0777, true);
        }
        $writer->save($p_path . $filename);
        $writer->save($r_path . $filename);
        return url('admin/dashboard/download')->build() . '?file=' . $filename;
    }
}
